package com.wyl.asynctask.service.impl;

import com.wyl.asynctask.entity.GoodsInfo;
import com.wyl.asynctask.service.IAsyncService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author: wyl
 * @date: 2021/10/12
 * @des:
 */
@Slf4j
@Service
public class AsyncServiceImpl implements IAsyncService {


    /**
     * 异步任务需要加上注解, 并指定使用的线程池
     *
     * @param goodsInfos
     * @param taskId
     */
    @SneakyThrows
    @Async("getAsyncExecutor")
    @Override
    public void asyncImportGoods(List<GoodsInfo> goodsInfos, String taskId) {

        log.info("async task running taskId: [{}]", taskId);

        StopWatch watch = StopWatch.createStarted();

        // 随机休眠，模拟业务耗时
        TimeUnit.SECONDS.sleep(new Random().nextInt(10));

        watch.stop();
        log.info("check and import goods success: [{}ms]", watch.getTime(TimeUnit.MILLISECONDS));
    }
}
